<script setup>
  import { getCodeApi } from '@/api/profile'
  import { useUserStore } from '@/stores'
  import { isValid, isEmpty } from '@/utils/checkForm'
  import { onLoad } from '@dcloudio/uni-app'
  import { ref } from 'vue'
  const userStore = useUserStore()
  const isAgree = ref(false)
  import pageJson from '@/pages.json'
  let redirectUrl = null

  onLoad((query) => {
    redirectUrl = query.redirectUrl
  })

  const onBack = () => {
    uni.navigateBack()
  }

  const gotoHomePage = () => {
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/index/index'
      })
    })
  }

  const isValidPhone = isValid(/^1[3-9]\d{9}$/)
  const isValidCode = isValid(/^\d{6}$/)

  // 验证码倒计时
  const timeLeft = ref(0)
  // 登录表单
  const loginForm = {
    phone: '13522513531', // 手机号
    code: '123456' // 验证码
  }
  let verifyCode = null
  // 获取验证码
  const getCode = async () => {
    const { phone } = loginForm
    // 校验手机号
    if (!checkPhone(phone)) return
    if (timeLeft.value > 0) return
    timeLeft.value = 60
    // 请求验证码
    verifyCode = await getCodeApi(phone)
    const timer = setInterval(() => {
      timeLeft.value--
      if (timeLeft.value === 0) {
        clearInterval(timer)
      }
    }, 1000)
  }

  // 校验手机号
  const checkPhone = (phone) => {
    // 校验手机号
    if (isEmpty(phone)) {
      uni.showToast({ title: '手机号不能为空', icon: 'none' })
      return false
    }
    if (!isValidPhone(phone)) {
      uni.showToast({ title: '手机号格式不正确', icon: 'none' })
      return false
    }
    return true
  }
  // 校验验证码
  const checkCode = (code) => {
    if (isEmpty(code)) {
      uni.showToast({ title: '验证码不能为空', icon: 'none' })
      return false
    }
    if (!isValidCode(code)) {
      uni.showToast({ title: '验证码格式不正确', icon: 'none' })
      return false
    }
    if (code !== verifyCode) {
      uni.showToast({ title: '验证码错误', icon: 'none' })
      return false
    }
    return true
  }
  // 登录按钮的加载状态
  const loading = ref(false)
  // 验证码登录
  const onLoginByCode = async () => {
    // 是否同意用户协议
    if (!isAgree.value)
      return uni.showToast({
        title: '请阅读并勾选协议',
        icon: 'none'
      })
    // 解构登录表单
    const { phone, code } = loginForm
    // 校验手机号
    if (!checkPhone(phone)) return
    // 校验验证码
    if (!checkCode(code)) return
    // 发起登录请求
    try {
      loading.value = true
      await userStore.loginByCodeAction(loginForm)
      uni.showToast({
        title: '登录成功'
      })
      setTimeout(() => {
        if (!redirectUrl) return uni.navigateBack()
        // 判断是不是 tabbar 页面
        const isTabbarPage = pageJson.tabBar.list.some((item) => item.pagePath === redirectUrl.slice(1))
        if (isTabbarPage) {
          uni.switchTab({
            url: redirectUrl
          })
        } else
          uni.redirectTo({
            url: redirectUrl
          })
      }, 1000)
    } catch (e) {
    } finally {
      loading.value = false
    }
  }

  const appid = 'wxced773bb27a21222'
  const secret = '46beb94b98e68f6b6d7ef263b9f165f2'
  // 微信手机号登录
  const onLoginByWx = async () => {
    if (!isAgree.value)
      return uni.showToast({
        title: '请阅读并勾选协议',
        icon: 'none'
      })
    uni.login({
      provider: 'weixin',
      success: async ({ code: js_code }) => {
        uni.request({
          method: 'get',
          url: 'https://api.weixin.qq.com/sns/jscode2session',
          data: {
            appid,
            secret,
            js_code
          },
          success: async (res) => {
            if (res.errMsg !== 'request:ok')
              return uni.showToast({
                title: '网络繁忙, 请稍后重试',
                icon: 'none'
              })
            try {
              loading.value = true
              await userStore.loginByWxAction(res.data.openid)
              uni.showToast({
                title: '登录成功',
                icon: 'success'
              })
              setTimeout(() => {
                if (!redirectUrl) return uni.navigateBack()
                // 判断是不是 tabbar 页面
                const isTabbarPage = pageJson.tabBar.list.some((item) => item.pagePath === redirectUrl.slice(1))
                if (isTabbarPage) {
                  uni.switchTab({
                    url: redirectUrl
                  })
                } else
                  uni.redirectTo({
                    url: redirectUrl
                  })
              }, 1000)
            } catch (e) {
            } finally {
              loading.value = false
            }
          },
          complete: () => {
            uni.hideLoading()
          }
        })
      }
    })
  }
</script>

<template>
  <bit-nav-bar
    title="比特租房"
    bgColor="#ebfbff"
  >
    <template #left>
      <image
        @click="onBack"
        class="icon"
        src="https://bitejiaoyan.oss-cn-chengdu.aliyuncs.com/bitehouse/web/profile/fanhui.png"
        mode="scaleToFill"
      />
      <image
        @click="gotoHomePage"
        class="icon"
        src="https://bitejiaoyan.oss-cn-chengdu.aliyuncs.com/bitehouse/web/profile/shouye.png"
        mode="scaleToFill"
      />
    </template>
  </bit-nav-bar>
  <scroll-view
    scroll-y
    class="login"
  >
    <view class="login-title"> 手机号快捷登录 </view>
    <text class="login-sub-title">未注册过的手机号将自动创建账号</text>
    <view class="login-form">
      <!-- 手机号 -->
      <view class="login-form-item phone">
        <input
          class="login-form-item__input"
          type="tel"
          placeholder="手机号"
          v-model="loginForm.phone"
        />
      </view>
      <!-- 验证码 -->
      <view class="login-form-item code">
        <input
          class="login-form-item__input"
          type="text"
          placeholder="验证码"
          v-model="loginForm.code"
        />
        <text
          class="login-form-item__code"
          @click="getCode"
          >{{ timeLeft ? `${timeLeft}秒后重新获取` : '获取验证码' }}</text
        >
      </view>
      <!-- 协议 -->

      <view
        class="login-form-xy"
        @click="isAgree = !isAgree"
      >
        <view class="login-form-xy__ck">
          <block>
            <image
              v-if="isAgree"
              class="icon_isAgree"
              src="https://bitejiaoyan.oss-cn-chengdu.aliyuncs.com/bitehouse/web/profile/selected.png"
              mode="widthFix"
            />
            <image
              v-else
              class="icon_isAgree"
              src="https://bitejiaoyan.oss-cn-chengdu.aliyuncs.com/bitehouse/web/profile/unselected.png"
              mode="widthFix"
            />
          </block>
        </view>

        <view class="login-form-xy__text">
          <text class="login-form-xy__text-default">打勾表示您阅读并同意</text>
          <text class="login-form-xy__text-active">《比特找房用户服务协议》</text>
          <text class="login-form-xy__text-default">和</text>
          <text class="login-form-xy__text-active">《比特找房隐私政策》</text>
        </view>
      </view>
      <!-- 登录按钮 -->
      <button
        :disabled="loading"
        class="btn_login"
        @click="onLoginByCode"
      >
        立即登录
      </button>
      <!-- 微信登录 -->
      <button
        class="btn-wx_login"
        hover-class="none"
        :disabled="loading"
        @click="onLoginByWx"
      >
        微信一键登录
      </button>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
  @import '@/styles/variable.scss';
  @import '@/styles/mixins.scss';
  .icon {
    width: 32rpx;
    height: 32rpx;
    &:last-child {
      margin-left: 60rpx;
    }
  }
  .login {
    box-sizing: border-box;
    position: fixed;
    top: 176rpx;
    left: 0;
    right: 0;
    @include bottom-safeArea;
    padding: 60rpx 52rpx;
    background-image: linear-gradient(to bottom, #ebfbff 10%, #dff8ff 60%, #f0fcff 100%);
    &-title {
      font-size: 42rpx;
      color: var(--text-color-dark);
      font-weight: 600;
    }
    &-sub-title {
      font-size: var(--font-size-xs);
      color: var(--text-color-light);
    }
    &-form {
      display: flex;
      flex-direction: column;
      justify-content: center;
      width: 100%;
      padding: 59rpx 0;
      &-item {
        border-radius: 24rpx;
        box-shadow: 0rpx 0rpx 6rpx 0rpx rgba(17, 167, 254, 0.2);
        backdrop-filter: blur(10px);
        background-color: #fff;
        &.phone {
          margin-bottom: 30rpx;
        }
        &.code {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        &__input {
          box-sizing: border-box;
          height: 110rpx;
          padding: 0 30rpx;
          font-size: var(--font-size-md);
          color: var(--text-color-middle);
          &::-webkit-input-placeholder {
            color: var(--text-color-light);
          }
        }
        &__code {
          margin-right: 30rpx;
          font-size: var(--font-size-md);
          color: var(--text-active-color);
        }
      }
      &-xy {
        display: flex;
        margin-top: 17rpx;
        &__ck {
          .icon_isAgree {
            position: relative;
            width: 23rpx;
            height: 23rpx;
            margin-right: 4rpx;
          }
        }
        &__text {
          font-size: var(--font-size-xs);
          &-default {
            color: var(--text-color-light);
          }
          &-active {
            color: var(--text-active-color);
          }
        }
      }
      .btn_login,
      .btn-wx_login {
        width: 100%;
        height: 113rpx;
        line-height: 113rpx;
        font-size: var(--font-size-md);
        font-weight: 600;
        border-radius: 24rpx;
      }
      .btn_login {
        margin: 85rpx 0 30rpx;
        background-image: linear-gradient(to right, #22cfff, #0fa1fe);
        color: #fff;
      }
      .btn-wx_login {
        border: 1rpx solid rgba(15, 161, 254, 1);
        color: #0fa1fe;
      }
    }
  }
</style>
